// src/components/ToolKit/EnvVarManager.tsx
import React, { useState } from 'react';
import { Card, Button, Input, Tabs, Table, Modal, Form, message } from 'antd';
import { useStore } from '../../stores';
import { observer } from "mobx-react-lite";
import * as styles from '../../assets/styles/toolkit/environment.module';

const { TabPane } = Tabs;

// 定义环境变量类型
interface EnvVariable {
  id: string;
  name: string;
  value: string;
  description: string;
}

// 定义环境参数类型
interface EnvParameter {
  id: string;
  name: string;
  value: string;
  description: string;
}

// 定义环境类型
interface Environment {
  id: string;
  name: string;
  description: string;
  variables: EnvVariable[];
  parameters: EnvParameter[];
}

const EnvironmentVarManager: React.FC = observer(() => {
  const store = useStore();
  
  // 示例数据
  const [environments, setEnvironments] = useState<Environment[]>([
    {
      id: 'default',
      name: '默认环境',
      description: '系统默认环境',
      variables: [
        { id: '1', name: 'base_url', value: 'https://api.example.com', description: '接口基础地址' },
        { id: '2', name: 'version', value: 'v1', description: 'API版本' }
      ],
      parameters: [
        { id: '1', name: 'timeout', value: '5000', description: '请求超时时间(ms)' },
        { id: '2', name: 'retry_times', value: '3', description: '失败重试次数' }
      ]
    },
    {
      id: 'test',
      name: '测试环境',
      description: '用于功能测试',
      variables: [
        { id: '1', name: 'base_url', value: 'https://test-api.example.com', description: '接口基础地址' },
        { id: '2', name: 'version', value: 'v1', description: 'API版本' }
      ],
      parameters: [
        { id: '1', name: 'timeout', value: '10000', description: '请求超时时间(ms)' },
        { id: '2', name: 'retry_times', value: '5', description: '失败重试次数' }
      ]
    }
  ]);
  
  const [currentEnvId, setCurrentEnvId] = useState<string>('default');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isVarModalVisible, setIsVarModalVisible] = useState(false);
  const [isParamModalVisible, setIsParamModalVisible] = useState(false);
  const [newEnvForm] = Form.useForm();
  const [newVarForm] = Form.useForm();
  const [newParamForm] = Form.useForm();

  // 获取当前环境
  const currentEnv = environments.find(env => env.id === currentEnvId) || environments[0];

  // 切换环境
  const switchEnvironment = (envId: string) => {
    setCurrentEnvId(envId);
  };

  // 显示添加环境模态框
  const showAddEnvModal = () => {
    setIsModalVisible(true);
  };

  // 隐藏添加环境模态框
  const hideAddEnvModal = () => {
    setIsModalVisible(false);
    newEnvForm.resetFields();
  };

  // 添加环境
  const addEnvironment = () => {
    newEnvForm.validateFields().then(values => {
      const newEnv: Environment = {
        id: 'env_' + Date.now(),
        name: values.name,
        description: values.description,
        variables: [],
        parameters: []
      };
      
      setEnvironments([...environments, newEnv]);
      hideAddEnvModal();
    });
  };

  // 添加全局变量
  const addGlobalVar = () => {
    setIsVarModalVisible(true);
    newVarForm.resetFields();
  };

  // 保存全局变量
  const saveGlobalVar = () => {
    newVarForm.validateFields().then(values => {
      const newVar: EnvVariable = {
        id: 'var_' + Date.now(),
        name: values.name,
        value: values.value,
        description: values.description
      };
      
      const updatedEnvs = environments.map(env => {
        if (env.id === currentEnvId) {
          return {
            ...env,
            variables: [...env.variables, newVar]
          };
        }
        return env;
      });
      
      setEnvironments(updatedEnvs);
      setIsVarModalVisible(false);
    });
  };

  // 更新全局变量
  const updateGlobalVar = (id: string, field: keyof EnvVariable, value: string) => {
    const updatedEnvs = environments.map(env => {
      if (env.id === currentEnvId) {
        const updatedVars = env.variables.map(variable => {
          if (variable.id === id) {
            return { ...variable, [field]: value };
          }
          return variable;
        });
        
        return { ...env, variables: updatedVars };
      }
      return env;
    });
    
    setEnvironments(updatedEnvs);
  };

  // 删除全局变量
  const deleteGlobalVar = (id: string) => {
    const updatedEnvs = environments.map(env => {
      if (env.id === currentEnvId) {
        return {
          ...env,
          variables: env.variables.filter(v => v.id !== id)
        };
      }
      return env;
    });
    
    setEnvironments(updatedEnvs);
  };

  // 添加全局参数
  const addGlobalParam = () => {
    setIsParamModalVisible(true);
    newParamForm.resetFields();
  };

  // 保存全局参数
  const saveGlobalParam = () => {
    newParamForm.validateFields().then(values => {
      const newParam: EnvParameter = {
        id: 'param_' + Date.now(),
        name: values.name,
        value: values.value,
        description: values.description
      };
      
      const updatedEnvs = environments.map(env => {
        if (env.id === currentEnvId) {
          return {
            ...env,
            parameters: [...env.parameters, newParam]
          };
        }
        return env;
      });
      
      setEnvironments(updatedEnvs);
      setIsParamModalVisible(false);
    });
  };

  // 更新全局参数
  const updateGlobalParam = (id: string, field: keyof EnvParameter, value: string) => {
    const updatedEnvs = environments.map(env => {
      if (env.id === currentEnvId) {
        const updatedParams = env.parameters.map(param => {
          if (param.id === id) {
            return { ...param, [field]: value };
          }
          return param;
        });
        
        return { ...env, parameters: updatedParams };
      }
      return env;
    });
    
    setEnvironments(updatedEnvs);
  };

  // 删除全局参数
  const deleteGlobalParam = (id: string) => {
    const updatedEnvs = environments.map(env => {
      if (env.id === currentEnvId) {
        return {
          ...env,
          parameters: env.parameters.filter(p => p.id !== id)
        };
      }
      return env;
    });
    
    setEnvironments(updatedEnvs);
  };

  // 保存配置
  const saveConfig = () => {
    message.success('配置已保存');
    console.log('当前环境配置:', environments);
    // 后续可以在这里调用 store.toolkit.saveEnvConfig(environments) 来持久化
  };

  // 导出配置
  const exportConfig = () => {
    const dataStr = JSON.stringify(environments, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    
    const link = document.createElement('a');
    link.href = URL.createObjectURL(dataBlob);
    link.download = 'environment_config.json';
    link.click();
  };

  // 全局变量表格列配置
  const variableColumns = [
    {
      title: '变量名',
      dataIndex: 'name',
      key: 'name',
      width: '20%',
      render: (_: any, record: EnvVariable) => (
        <Input 
          value={record.name} 
          onChange={e => updateGlobalVar(record.id, 'name', e.target.value)} 
        />
      )
    },
    {
      title: '变量值',
      dataIndex: 'value',
      key: 'value',
      width: '40%',
      render: (_: any, record: EnvVariable) => (
        <Input 
          value={record.value} 
          onChange={e => updateGlobalVar(record.id, 'value', e.target.value)} 
        />
      )
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: '25%',
      render: (_: any, record: EnvVariable) => (
        <Input 
          value={record.description} 
          onChange={e => updateGlobalVar(record.id, 'description', e.target.value)} 
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      width: '15%',
      render: (_: any, record: EnvVariable) => (
        <Button 
          type="primary" 
          danger 
          size="small"
          onClick={() => deleteGlobalVar(record.id)}
        >
          删除
        </Button>
      )
    }
  ];

  // 全局参数表格列配置
  const parameterColumns = [
    {
      title: '参数名',
      dataIndex: 'name',
      key: 'name',
      width: '20%',
      render: (_: any, record: EnvParameter) => (
        <Input 
          value={record.name} 
          onChange={e => updateGlobalParam(record.id, 'name', e.target.value)} 
        />
      )
    },
    {
      title: '参数值',
      dataIndex: 'value',
      key: 'value',
      width: '40%',
      render: (_: any, record: EnvParameter) => (
        <Input 
          value={record.value} 
          onChange={e => updateGlobalParam(record.id, 'value', e.target.value)} 
        />
      )
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: '25%',
      render: (_: any, record: EnvParameter) => (
        <Input 
          value={record.description} 
          onChange={e => updateGlobalParam(record.id, 'description', e.target.value)} 
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      width: '15%',
      render: (_: any, record: EnvParameter) => (
        <Button 
          type="primary" 
          danger 
          size="small"
          onClick={() => deleteGlobalParam(record.id)}
        >
          删除
        </Button>
      )
    }
  ];

  return (
    <div className={styles.container}>
      <div className={styles.varHeader}>
        <h1 className={styles.varHeaderTitle}></h1>
        <div>
          <Button 
            type="primary" 
            className={`${styles.btn} ${styles.btnPrimary}`}
            onClick={saveConfig}
            style={{ marginRight: '10px' }}
          >
            保存配置
          </Button>
          <Button 
            type="primary" 
            className={`${styles.btn} ${styles.btnSuccess}`}
            onClick={exportConfig}
            style={{ marginRight: '10px' }}
          >
            导出配置
          </Button>
          <Button className={styles.btn}>
            导入配置
          </Button>
        </div>
      </div>
      
      <Card className={styles.card}>
        <div className={styles.cardHeader}>
          <h3 className={styles.cardHeaderTitle}>环境选择</h3>
          <div>
            <Button 
              type="primary" 
              size="small"
              className={`${styles.btn} ${styles.btnSmall}`}
              onClick={showAddEnvModal}
            >
              添加环境
            </Button>
          </div>
        </div>
        <div className={styles.cardBody}>
          <div className={styles.envTabs}>
            {environments.map(env => (
              <div 
                key={env.id}
                className={`${styles.envTab} ${env.id === currentEnvId ? styles.envTabActive : ''}`}
                onClick={() => switchEnvironment(env.id)}
              >
                {env.name}
              </div>
            ))}
          </div>
          
          <Tabs defaultActiveKey="1">
            <TabPane tab="全局变量" key="1">
              <Card className={styles.card}>
                <div className={styles.cardHeader}>
                  <h3 className={styles.cardHeaderTitle}>全局变量</h3>
                  <Button 
                    type="primary" 
                    size="small"
                    className={`${styles.btn} ${styles.btnSmall}`}
                    onClick={addGlobalVar}
                  >
                    添加变量
                  </Button>
                </div>
                <div className={styles.cardBody}>
                  {currentEnv.variables.length > 0 ? (
                    <Table 
                      dataSource={currentEnv.variables} 
                      columns={variableColumns} 
                      pagination={false}
                      rowKey="id"
                    />
                  ) : (
                    <div className={styles.emptyState}>
                      <p>暂无全局变量，点击"添加变量"按钮创建</p>
                    </div>
                  )}
                </div>
              </Card>
            </TabPane>
            
            <TabPane tab="全局参数" key="2">
              <Card className={styles.card}>
                <div className={styles.cardHeader}>
                  <h3 className={styles.cardHeaderTitle}>全局参数</h3>
                  <Button 
                    type="primary" 
                    size="small"
                    className={`${styles.btn} ${styles.btnSmall}`}
                    onClick={addGlobalParam}
                  >
                    添加参数
                  </Button>
                </div>
                <div className={styles.cardBody}>
                  {currentEnv.parameters.length > 0 ? (
                    <Table 
                      dataSource={currentEnv.parameters} 
                      columns={parameterColumns} 
                      pagination={false}
                      rowKey="id"
                    />
                  ) : (
                    <div className={styles.emptyState}>
                      <p>暂无全局参数，点击"添加参数"按钮创建</p>
                    </div>
                  )}
                </div>
              </Card>
            </TabPane>
          </Tabs>
        </div>
      </Card>

      {/* 添加环境模态框 */}
      <Modal
        title="添加环境"
        visible={isModalVisible}
        onOk={addEnvironment}
        onCancel={hideAddEnvModal}
        okText="确认"
        cancelText="取消"
      >
        <Form form={newEnvForm} layout="vertical">
          <Form.Item 
            name="name" 
            label="环境名称" 
            rules={[{ required: true, message: '请输入环境名称' }]}
          >
            <Input placeholder="例如：测试环境、生产环境" />
          </Form.Item>
          <Form.Item 
            name="description" 
            label="环境描述"
          >
            <Input placeholder="环境的简要描述" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加变量模态框 */}
      <Modal
        title="添加变量"
        visible={isVarModalVisible}
        onOk={saveGlobalVar}
        onCancel={() => setIsVarModalVisible(false)}
        okText="确认"
        cancelText="取消"
      >
        <Form form={newVarForm} layout="vertical">
          <Form.Item 
            name="name" 
            label="变量名" 
            rules={[{ required: true, message: '请输入变量名' }]}
          >
            <Input placeholder="变量名" />
          </Form.Item>
          <Form.Item 
            name="value" 
            label="变量值"
            rules={[{ required: true, message: '请输入变量值' }]}
          >
            <Input placeholder="变量值" />
          </Form.Item>
          <Form.Item 
            name="description" 
            label="描述"
          >
            <Input placeholder="描述" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加参数模态框 */}
      <Modal
        title="添加参数"
        visible={isParamModalVisible}
        onOk={saveGlobalParam}
        onCancel={() => setIsParamModalVisible(false)}
        okText="确认"
        cancelText="取消"
      >
        <Form form={newParamForm} layout="vertical">
          <Form.Item 
            name="name" 
            label="参数名" 
            rules={[{ required: true, message: '请输入参数名' }]}
          >
            <Input placeholder="参数名" />
          </Form.Item>
          <Form.Item 
            name="value" 
            label="参数值"
            rules={[{ required: true, message: '请输入参数值' }]}
          >
            <Input placeholder="参数值" />
          </Form.Item>
          <Form.Item 
            name="description" 
            label="描述"
          >
            <Input placeholder="描述" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
});

export default EnvironmentVarManager;